﻿using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.UI;
using AVIS.OutBound.Notify;
using AVIS.OutBound.Orders;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AVIS.OutBound.ThirdOrders
{
    /// <summary>
    /// AA接机订单的领域对象
    /// </summary>
    public class AAOrderManager : DomainService, IAAOrderManager
    {
        #region 构造函数
        /// <summary>
        /// 接机EMILA
        /// </summary>
        private static string JIEJIEMAIL = ConfigurationManager.AppSettings["jiejiemail"];
        private readonly IRepository<AAOrder> _orderRepository;
        private readonly INotifyManager _notifyManager;

        public AAOrderManager(
            IRepository<AAOrder> orderRepository,
            NotifyManager notifyManager)
        {
            _orderRepository = orderRepository;
            _notifyManager = notifyManager;
        }
        #endregion

        /// <summary>
        /// 判断是否存在指定Avis订单号的AA接机订单
        /// </summary>
        /// <param name="avisOrderNo">(必填)AVIS订单号</param>
        /// <returns></returns>
        public bool IsExist(string avisOrderNo)
        {
            if (string.IsNullOrEmpty(avisOrderNo))
                return false;

            var count = _orderRepository.Count(a => a.ReservationNumber == avisOrderNo &&
                ((a.AANo != "" && a.AAStatus == 2) || a.AAStatus == 1));

            return count > 0;
        }

        /// <summary>
        /// 取消AA接机订单
        /// </summary>
        /// <param name="avisOrderNo">(必填)AVIS订单号</param>
        /// <returns></returns>
        public bool CancelAAOrder(string avisOrderNo)
        {
            if (string.IsNullOrEmpty(avisOrderNo))
            {
                throw new UserFriendlyException("取消YouYou订单需要输入Aivs订单号！");
            }

            int? AAStatus = 0;
            var AAOrder = _orderRepository.FirstOrDefault(o => o.ReservationNumber == avisOrderNo);
            if (AAOrder != null)
            {
                AAStatus = AAOrder.AAStatus;
                AAOrder.AAStatus = 4;
                AAOrder.CancelDate = DateTime.Now;
                _orderRepository.Update(AAOrder);

                if (AAStatus == 1)
                {
                    _notifyManager.SendMail(JIEJIEMAIL, "接机取消", AAOrder.ReservationNumber);
                }
            }

            return false;
        }

        /// <summary>
        /// 新插入AA接机订单
        /// </summary>
        /// <param name="order">Avis订单</param>
        /// <returns></returns>
        public bool SaveOrder(Order order)
        {
            var aaOrder = new AAOrder
            {
                ReservationNumber = order.OrderNo,
                AAStatus = 6,
                BookingDate = DateTime.Parse("1900-01-01"),
                ConfirmDate = DateTime.Parse("1900-01-01"),
                CancelDate = DateTime.Parse("1900-01-01"),
                PickupTime = DateTime.Parse("1900-01-01"),
                CreateDate = Abp.Timing.Clock.Now,
                ModifyDate = Abp.Timing.Clock.Now,
            };
            var id = _orderRepository.InsertAndGetId(aaOrder);

            return true;
        }

        /// <summary>
        /// 更新AA接机订单到完成状态，真正用户提交AA订单的步骤，同时发生邮件通知
        /// 说明：在租车预订单提交过程中，会默认产生一个空的AA订单，然后在租车订单详情中点击链接才能完成AA接机订单的提交
        /// </summary>
        /// <param name="aaOrder">AA接机订单</param>
        /// <returns></returns>
        public bool UpdateOrderToCompleted(AAOrder aaOrder)
        {
            var dbOrder = GetDBOrder(aaOrder.ReservationNumber);
            if (dbOrder == null || dbOrder.AAStatus != 6)
            {
                throw new UserFriendlyException("接机预订订单可能已经提交了，请查看邮件。");
            }

            dbOrder.AANo = ""; // 现在不需要回写AANo了，采用发邮件的方式
            dbOrder.AAStatus = 1;
            dbOrder.BookingDate = Abp.Timing.Clock.Now;
            dbOrder.PickupTime = aaOrder.PickupTime;
            dbOrder.Username = aaOrder.Username;
            dbOrder.Mobile = aaOrder.Mobile;
            dbOrder.Childseat = aaOrder.Childseat;
            dbOrder.Pickupadd = aaOrder.Pickupadd;
            dbOrder.Address = aaOrder.Address;
            dbOrder.FlightNo = aaOrder.FlightNo;
            dbOrder.Carlevel = aaOrder.Carlevel;
            dbOrder.Email = aaOrder.Email;

            _orderRepository.Update(dbOrder);

            // 发送AA接机订单预订成功的通知邮件
            var templateParameters = dbOrder.ReservationNumber + OutBoundConsts.SysSeparator;
            templateParameters += (dbOrder.PickupTime.HasValue ? dbOrder.PickupTime.Value.ToString("yyyy年MM月dd日 HH:mm") : "") + OutBoundConsts.SysSeparator;
            templateParameters += dbOrder.Username + OutBoundConsts.SysSeparator;
            templateParameters += dbOrder.Mobile + OutBoundConsts.SysSeparator;
            templateParameters += dbOrder.Childseat + OutBoundConsts.SysSeparator;
            templateParameters += dbOrder.Pickupadd + OutBoundConsts.SysSeparator;
            templateParameters += dbOrder.Address + OutBoundConsts.SysSeparator;
            templateParameters += dbOrder.FlightNo + OutBoundConsts.SysSeparator;
            templateParameters += (dbOrder.Carlevel == 1 ? "公务车" : "商务车") + OutBoundConsts.SysSeparator;
            templateParameters += dbOrder.Email;
            _notifyManager.SendMail(JIEJIEMAIL, "接机预定", templateParameters);

            return true;
        }

        /// <summary>
        /// 获取AA接机订单的详情信息（本地DB）
        /// </summary>
        /// <param name="avisOrderNo">(必填)AVIS订单号</param>
        /// <returns></returns>
        public AAOrder GetDBOrder(string avisOrderNo)
        {
            var AAOrder = _orderRepository.FirstOrDefault(o => o.ReservationNumber == avisOrderNo);
            return AAOrder;
        }
    }
}
